//
//  EMCategoryViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 14/12/21.
//  Copyright (c) 2014年 cczu. All rights reserved.
//

#import "EMCategoryViewController.h"
#import "UINavigationController+EMNavi.h"
#import "EMSearchBar.h"
#import "EMCityChooseViewController.h"
#import "EMSearchViewController.h"
#import "MyLayout.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "EMCatSegmentedController.h"
#import "EMGetLevel1InfoReqBody.h"
#import "EMGetLevel1InfoRespBody.h"
#import "EMGetLevel2InfoReqBody.h"
#import "EMGetLevel2InfoRespBody.h"
#import "EMCateListViewController.h"

@interface EMCategoryViewController ()
{
    UITextField *tf0;
    AppDelegate * app;
    NSArray *level1Array;
    NSArray *level2Array;
    UITableView *catTable;
    NSMutableArray *openFlagArray;
    NSIndexPath *lastIndexPath;
    NSArray *innerTitleArray;
}

@end

@implementation EMCategoryViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.view.backgroundColor = [UIColor whiteColor];
    
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    level1Array = [[NSArray alloc] init];
    level2Array = [[NSArray alloc] init];
    openFlagArray = [[NSMutableArray alloc] init];
    innerTitleArray = [[NSArray alloc] init];
    EMSearchBar *search = [[EMSearchBar alloc] initWithFrame:CGRectMake(0, 0, 140, 24)];
    search.placeholderText = @"点击搜索商品";
    for (UIView *tf in search.subviews) {
        if ([tf isKindOfClass:[UITextField class]]) {
            tf0 = (UITextField *)tf;
        }
    }
    tf0.delegate = self;
    self.navigationItem.titleView = search;
    
    UIBarButtonItem *logoImage = [[UIBarButtonItem alloc] init];
    UIImage *imageQ = [UIImage imageNamed:@"logo_导航"];
    UIImageView *leftView = [[UIImageView alloc] initWithImage:[imageQ imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    leftView.frame = CGRectMake(0, 0, 90, 23);
    logoImage.customView = leftView;
    self.navigationItem.leftBarButtonItem = logoImage;
    
    UIButton *cityButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cityButton.frame = CGRectMake(270, 6, 60, 24);
    [cityButton setImage:[UIImage imageNamed:@"icon_地址选择"] forState:UIControlStateNormal];
    [cityButton setTitle:@"南京" forState:UIControlStateNormal];
    [cityButton setTitleColor:RGB(101, 118, 32) forState:UIControlStateNormal];
    cityButton.titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [cityButton addTarget:self action:@selector(chooseCity:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cityItem = [[UIBarButtonItem alloc] init];
    cityItem.customView = cityButton;
    self.navigationItem.rightBarButtonItem = cityItem;
    
    
    
    [self getLevel2InfoWithMenuId:@"20150104113705"];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    EMSearchViewController *controller = [[EMSearchViewController alloc] init];
    UINavigationController *navi2 = [[UINavigationController alloc] initWithRootViewController:controller];
    [self presentViewController:navi2 animated:YES completion:nil];
}
- (void)chooseCity:(UIButton *)sender
{
//    EMCityChooseViewController *controller = [[EMCityChooseViewController alloc] init];
//    [self presentViewController:controller animated:YES completion:nil];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self getLevel1Info];
    [self createTableView];
    
    EMCatSegmentedController *seg = [[EMCatSegmentedController alloc] initWithFrame:CGRectMake(0, 64, 80, level1Array.count * 50)];
    NSMutableArray *level1TitleArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < level1Array.count; i ++) {
        NSDictionary *aLevel = level1Array[i];
        [level1TitleArray addObject:aLevel[@"name"]];
    }
    [seg setTitleArray:[level1TitleArray mutableCopy]];
    [seg setActionBlock:^(NSUInteger index) {
        [self getLevel1Info];
        NSDictionary *aLevel = level1Array[index];
        [openFlagArray removeAllObjects];
        [self getLevel2InfoWithMenuId:aLevel[@"id"]];
    }];
    [self.view addSubview:seg];
}

- (void)getLevel1Info
{
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    EMGetLevel1InfoReqBody *reqBody = [[EMGetLevel1InfoReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"MENU-LIST";
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMGetLevel1InfoRespBody *respBody = [EMGetLevel1InfoRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            level1Array = respBody.SUCCESSFULINFO;
            
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    
}

- (void)getLevel2InfoWithMenuId:(NSString *)menuId
{
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    EMGetLevel2InfoReqBody *reqBody = [[EMGetLevel2InfoReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"MENU-INFO";
    reqBody.MENUID = menuId;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMGetLevel2InfoRespBody *respBody = [EMGetLevel2InfoRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            level2Array = respBody.SUCCESSFULINFO;
            for (int i = 0; i < level2Array.count; i ++) {
                [openFlagArray addObject:@(NO)];
            }
            
            [catTable reloadData];
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    
}
- (void)createTableView
{
    CGRect catRect = [UIScreen mainScreen].bounds;
    catRect.origin.x = 80;
    catRect.size.width = [UIScreen mainScreen].bounds.size.width - 80;
    catTable = [[UITableView alloc] init];
    catTable.frame = catRect;
    catTable.delegate = self;
    catTable.dataSource = self;
    catTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:catTable];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return level2Array.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    for (int i = 0; i < openFlagArray.count; i ++) {
        if ([openFlagArray[i] boolValue] == YES) {
            if (section == i) {
                return 2;
            } else {
                return 1;
            }
        }
        
    }
    return 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"catgCell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:cellIdentifier];
    }
    NSDictionary *aLevel = level2Array[indexPath.section];
    if (indexPath.row == 0) {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, cell.frame.size.width-10, 0.5)];
        lineView.backgroundColor = RGB(112, 179, 81);
        [cell addSubview:lineView];
        cell.textLabel.text = aLevel[@"name"];
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.textLabel.font = [UIFont fontWithName:HEITILIGHT size:13];
        UIImageView *clous = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_二级菜单未展开"]];
        clous.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 45-80, cell.frame.size.height / 2 - 15, 30, 30);
        
        if ([openFlagArray[indexPath.section] boolValue]) {
            clous.transform = CGAffineTransformMakeRotation(M_PI / 2);
        } else {
            clous.transform = CGAffineTransformMakeRotation(0);
        }
        [cell addSubview:clous];
    } else {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, 100, cell.frame.size.width-10, 0.5)];
        lineView.backgroundColor = RGB(112, 179, 81);
        [cell addSubview:lineView];
        CGRect aFrame = cell.frame;
        aFrame.origin.x = 20;
        aFrame.size.width = cell.frame.size.width - 40;
        aFrame.size.height = 100;
        MyLayout *layout = [[MyLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        UICollectionView *innerCollectionView = [[UICollectionView alloc] initWithFrame:aFrame collectionViewLayout:layout];
        innerCollectionView.delegate = self;
        innerCollectionView.dataSource = self;
        [innerCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"catInnerCell"];
        innerCollectionView.backgroundColor = [UIColor whiteColor];
        [cell addSubview:innerCollectionView];
    }
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 40;
    } else {
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if ([openFlagArray[indexPath.section] boolValue] == YES) {
            
            [openFlagArray replaceObjectAtIndex:indexPath.section withObject:@(NO)];
        } else {
            for (int i = 0; i < level2Array.count; i ++) {
                NSDictionary *aInner = level2Array[i];
                if (i == indexPath.section) {
                    if ([[aInner allKeys] containsObject:@"child"]) {
                        innerTitleArray = aInner[@"child"];
                    } else {
                        innerTitleArray = @[@{@"id": @"majury", @"name": @"暂无"}];
                    }
                }
                
                
            }
            if (lastIndexPath.section <= openFlagArray.count) {
                [openFlagArray replaceObjectAtIndex:lastIndexPath.section withObject:@(NO)];
            }
            
            [openFlagArray replaceObjectAtIndex:indexPath.section withObject:@(YES)];
        }
        lastIndexPath = indexPath;
        [tableView reloadData];
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return innerTitleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"catInnerCell" forIndexPath:indexPath];
    NSDictionary *aDic = innerTitleArray[indexPath.item];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:cell.bounds];
    titleLabel.text = aDic[@"name"];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.layer.borderWidth = 1;
    titleLabel.layer.borderColor = RGB(112, 179, 81).CGColor;
    titleLabel.layer.cornerRadius = 5;
    [cell addSubview:titleLabel];
    cell.backgroundColor = [UIColor clearColor];
    [cell sizeToFit];
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    UIEdgeInsets top = {0, 0, 0, 0};
    return top;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *aDic = innerTitleArray[indexPath.item];
    NSString *titleC = aDic[@"name"];
    NSDictionary *attDic = @{NSFontAttributeName: [UIFont systemFontOfSize:12]};
    CGSize fontSize = [titleC sizeWithAttributes:attDic];
    return CGSizeMake(fontSize.width + 10, 20);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *aDic = innerTitleArray[indexPath.item];
    NSLog(@"%@", aDic[@"id"]);
    EMCateListViewController *controller = [[EMCateListViewController alloc] init];
    controller.listId = aDic[@"id"];
    controller.hidesBottomBarWhenPushed = YES;
    if (![aDic[@"id"] isEqualToString:@"majury"]) {
        [self.navigationController pushViewController:controller animated:YES];
    } else {
        [app showTip:@"没有商品哦"];
    }
    
}


@end
